package com.bjfu.demo.exception;

import com.bjfu.demo.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

@Slf4j
@RestControllerAdvice(basePackages = "com.bjfu.demo.controller")
public class ReleaseExceptionControllerAdvice {
//    @ExceptionHandler(value = MethodArgumentNotValidException.class)
//    public Result<List<FieldError>> handleValidException(MethodArgumentNotValidException e) {
//        log.error(e.getMessage(), e.getClass());
//        BindingResult bindingResult = e.getBindingResult();
//        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//        return Result.fail("传值错误", fieldErrors);
//    }

    @ExceptionHandler(value = BindException.class)
    public Result<HashMap<String, String>> handleException(BindException e) {
        log.error(e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        HashMap<String, String> resultData = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            resultData.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return Result.fail("传值错误", resultData);
    }
}
